import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution4 {
    public static List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> ret = new ArrayList<>();
        int n = nums.length;
        for (int i = 0; i < n-2; i++) {
            if (nums[i] > 0) {
                break;
            }
            int left = i + 1,right = n-1;
            if (i > 0 && nums[i] == nums[i-1]) {
                continue;
            }
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum < 0) {
                    left++;
                } else if (sum > 0) {
                    right--;
                } else {
                    ret.add(Arrays.asList(nums[i],nums[left],nums[right]));
                    while (left < right && nums[right] == nums[right-1]) right--;
                    while (left < right && nums[left] == nums[left+1]) left++;
                    right--;
                    left++;
                }


            }
        }
        return ret;
    }

    public static void main(String[] args) {
        int[] nums = {1,-1,-1,0};
        threeSum(nums);
    }
}
